package com.foo.TextPreProcessing;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

public class TrimXMLTest {
	public static void main( String[] args ){
		System.out.println("test");

		TrimXMLTest test = new TrimXMLTest();
		String fileName = "C:\\Users\\Avanti\\Desktop\\SJSU\\CMPE 239 - Web and Data Mining\\Project\\DATA MINING DATA SETS\\newsSpace\\testTrimXML.xml";
		String tagFilter = "url";

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		Document document = null;

		try{
			builder = factory.newDocumentBuilder();
			document = builder.parse( new File( fileName ) );
			test.filterElements( document, tagFilter );
			test.printNodeElements(document);
		} catch ( Exception e ){
			e.printStackTrace();
		}
	}


	/*
	 * filter all elements whose tag name = filter
	 */
	public void filterElements( Node parent, String filter ){
		NodeList children = parent.getChildNodes();

		for( int i=0; i < children.getLength(); i++ ){
			Node child = children.item( i );

			// only interested in elements
			if( child.getNodeType() == Node.ELEMENT_NODE ){

				// remove elements whose tag name  = filter
				// otherwise check its children for filtering with a recursive call
				if( child.getNodeName().equals(filter) ){
					parent.removeChild( child );
				} else {
					filterElements( child, filter );
				}
			}
		}
	}

	/*
	 * print a nodes elements and children
	 */
	public void printNodeElements( Node node ){
		System.out.println( node.getNodeName() );

		NodeList children = node.getChildNodes();

		for ( int i = 0; i < children.getLength(); i++ ){
			Node child = children.item( i );

			if( child.getNodeType() == Node.ELEMENT_NODE ){
				printNodeElements( child );
			}
		}
	}
}
